const DATA = (() => {
    let data = localStorage.getItem('DATA_book_room');
    if (data) {
        data = {
            vm: JSON.parse(data),
            vmPopupDateBox: JSON.parse(localStorage.getItem('DATA_vmPopupDateBox')),
        };
        localStorage.removeItem('DATA_book_room');
        localStorage.removeItem('DATA_vmPopupDateBox');
    }
    else {
        data = {
            vm: {
                roomSubmit: {
                    switch: false,
                    total: '0',
                    rent: '0',
                    insure: '0',
                    deposit: '0',
                },
                infoDate: {
                    startDate: '请选择入住日期',
                    dayList: [],
                    endDate: '退房日期',
                    nightNum: '',
                    guysList: [],
                    guysShowText: '4',
                    guysSelected: false,
                    tel: '',
                    insuranceNum: 0 // 需要保险人数
                },
                houseInfo: {
                    people: 0,
                },
            },
            vmPopupDateBox: {
                selectDateList: [],
                dateList: [],
                dayLength: 0,
                choosable: true,
                selectDate: {
                    start: '--',
                    startDay: null,
                    end: '--',
                    endDay: null,
                    nightNum: '--',
                    todayIndex: 0,
                    firstYet: null,
                },
                popupShow: false,
            },
        };
    }
    return data;
})();

const vm = new Vue({
    el: '#main',
    data: DATA.vm,
    methods: {
        toggleSwitch() {
            this.roomSubmit.switch = !this.roomSubmit.switch;
        },
        datePopupShow,
    },
    mounted() {
        document.getElementById('popupDateBox').style.display = '-webkit-flex';
    },
});

/* * * * * * * *
 *  日期选择框框 *
 * * * * * * * */
const vmPopupDateBox = new Vue({
    el: '#popupDateBox',
    data: DATA.vmPopupDateBox,
    methods: {
        select,
    },
});

function apiready() {
    fxj.fixLayout();
    fixPriceDetailBoxLayout();
    getGuysIdList();

    if (!localStorage.getItem('DATA_vmPopupDateBox')) {
        initSelectDateBox.call(vmPopupDateBox);
    }

    saveVueData();
    setPrice(Number(vm.roomSubmit.rent));
    reqHouseInfo();
}

function fixPriceDetailBoxLayout() {
    const h = document.querySelector('.room-submit').offsetHeight;
    document.querySelector('.room-price-detail').style.paddingBottom = h + 'px';
    document.getElementById('main').style.marginBottom = h + 'px';
}

/* * * * * * * *
 *  日期选择框框 *
 * * * * * * * */
function datePopupShow() {
    vmPopupDateBox.popupShow = true;
    const html = document.querySelector('html');
    html.classList.add('no-scroll');
    if (vmPopupDateBox.selectDate.end !== '--') {
        clearSelectedDate();
        clearTempBan();
    }
}

async function closeDatePopup(ok) {
    vmPopupDateBox.popupShow = false;
    const html = document.querySelector('html');
    html.classList.remove('no-scroll');
    if (ok) {
        let sent = await getRentPrice();
        setPrice(sent);
        saveVueData();
    }
}

async function initSelectDateBox() {
    // 请求服务器获取房源日期列表
    const data = await getHouseResDateInfo();
    let tempDataArr = []; // 不这么绕一圈,vue监听不到数据变化  囧
    // 把原始数据格式化为需要格式
    data.forEach((month, monthIndex) => {
        tempDataArr[monthIndex] = {
            date: '', // 当前 年-月
            startWeek: 0, // 当月第一天星期几
            child: [], // 当月的所有日期
        };
        month.forEach((day, dayIndex) => {
            const dayInfo = { // 使vue监听数据
                year: day.date.substr(0, 4),
                month: (+(day.date.substr(4, 2))).toString(),
                day: (+(day.date.substr(6, 2))).toString(),
                price: day.discount_price === 0 ? day.price : day.discount_price,
                yet: Number(day.is_rent) !== 0, // 当天已租?
                week: day.week,
                index: this.dayLength, // 线性表索引
                start: false,
                mid: false,
                end: false,
            };
            // 日期是否已经过期
            dayInfo.outmoded = new Date(`${dayInfo.year}/${dayInfo.month}/${dayInfo.day}`) - getToday();
            if (dayInfo.outmoded === 0) {
                this.selectDate.todayIndex = dayInfo.index;
            }
            dayInfo.ban = dayInfo.yet || dayInfo.outmoded < 0; // 当天不可选?

            tempDataArr[monthIndex].child[dayIndex] = dayInfo;
            tempDataArr[monthIndex].date = `${dayInfo.year}-${dayInfo.month}`;
            (dayIndex === 0) && (tempDataArr[monthIndex].startWeek = dayInfo.week);
            this.dayLength++;
        });
        this.selectDateList.push(...tempDataArr[monthIndex].child);
    });
    vmPopupDateBox.dateList = tempDataArr;
}

function getToday() {
    const t = new Date(new Date().toLocaleDateString());
    getToday = () => {
        return t;
    };
    return t;
}

function select(day) {
    if (vmPopupDateBox.selectDate.start === '--') {
        setSelectDay(day, 'start');
        const schipolDay = findSchipolHouse(day.index);
        vm.infoDate.dayList.push(day);
        if (schipolDay) { // 第一个已出租日期
            changeSchipolHouseStatus(schipolDay);
            setBanElem(day.index, schipolDay.index);
        }
        else {
            setBanElem(day.index, -1);
        }
    }
    else if (
        day.index !== vmPopupDateBox.selectDate.startDay.index &&
        vmPopupDateBox.selectDate.end === '--'
    ) {
        vm.infoDate.dayList.push(day);
        setSelectDay(day, 'end');
        setMidEl(vmPopupDateBox.selectDate);
        setNightNum(vmPopupDateBox.selectDate.startDay.index, vmPopupDateBox.selectDate.endDay.index);
    }
    else if (vmPopupDateBox.selectDate.end !== '--') {
        clearSelectedDate();
        clearTempBan();
    }
}

async function getHouseResDateInfo() {
    const date = new Date();
    const res = await ajax({
        url: 'home/houseDetail/getMonthPriceStatus',
        data: {
            houseId: getHouseId(),
            time: `${date.getFullYear()}/${date.getMonth()}/1`,
        },
    });
    if (res.err !== 0) {
        console.error(res);
    }
    return Promise.resolve(res.data);
}

function setSelectDay(day, type) {
    if (type === 'start') {
        vm.infoDate.startDate = `${day.year}.${day.month}.${day.day}`;
    }
    else if (type === 'end') {
        vm.infoDate.endDate = `${day.year}.${day.month}.${day.day}`;
    }
    vmPopupDateBox.selectDate[type] = `${day.month}月${day.day}日`;
    vmPopupDateBox.selectDate[`${type}Day`] = day;
    day[type] = true;
}

function findSchipolHouse(i) {
    const el = vmPopupDateBox.selectDateList[i];
    if (!el) return null;
    if (el.yet) return el;
    return findSchipolHouse(++i);
}

function changeSchipolHouseStatus(day) {
    vmPopupDateBox.selectDate.firstYet = day;
    day.ban = false;
}

function setBanElem(startEl, rightStartEl) {
    while (true) {
        startEl--;
        if (vmPopupDateBox.selectDateList[startEl]) {
            vmPopupDateBox.selectDateList[startEl].ban = true;
        }
        else {
            break;
        }
    }

    if (rightStartEl !== -1) {
        while (true) {
            rightStartEl++;
            if (vmPopupDateBox.selectDateList[rightStartEl]) {
                vmPopupDateBox.selectDateList[rightStartEl].ban = true;
            }
            else {
                break;
            }
        }
    }
}

function setMidEl(selectDate) {
    let [start, end] = [selectDate.startDay.index, selectDate.endDay.index];
    start++;
    for (; start < end; start++) {
        vmPopupDateBox.selectDateList[start].mid = true;
        vm.infoDate.dayList.push(vmPopupDateBox.selectDateList[start]);
    }
}

function setNightNum(start, end) {
    vm.infoDate.nightNum = `${end - start}`;
    vmPopupDateBox.selectDate.nightNum = `${end - start}晚`;
}

function clearSelectedDate() {
    vmPopupDateBox.selectDate.start = '--';
    vmPopupDateBox.selectDate.end = '--';
    vmPopupDateBox.selectDate.nightNum = '--';
    vmPopupDateBox.selectDate.startDay.start = false;
    vmPopupDateBox.selectDate.endDay.end = false;
    vm.infoDate.dayList = [];
    vm.infoDate.startDate = '请选择入住日期';
    vm.infoDate.endDate = '退房日期';
    let start = vmPopupDateBox.selectDate.startDay.index + 1;
    let end = vmPopupDateBox.selectDate.endDay.index;
    while (start < end) {
        vmPopupDateBox.selectDateList[start].mid = false;
        start++;
    }
    vmPopupDateBox.selectDate.startDay = null;
    vmPopupDateBox.selectDate.endDay = null;
}

function clearTempBan() {
    let i = vmPopupDateBox.selectDate.todayIndex;
    let end = vmPopupDateBox.selectDateList.length;
    while (i < end) {
        if (!vmPopupDateBox.selectDateList[i].yet) {
            vmPopupDateBox.selectDateList[i].ban = false;
        }
        i++;
    }
    if (vmPopupDateBox.selectDate.firstYet) {
        vmPopupDateBox.selectDate.firstYet.ban = true;
        vmPopupDateBox.selectDate.firstYet = null;
    }
}

function getHouseId() {
    return fxj.getSearch().get('id');
}

function getGuysIdList() {
    const guysIdList = localStorage.getItem('guysIdList');
    if (guysIdList) {
        vm.infoDate.guysList = JSON.parse(guysIdList);
        let needInsuranceNum = 0;
        vm.infoDate.guysList.forEach(guy => {
            if (isExist(guy.needInsurance) && guy.needInsurance) {
                needInsuranceNum++;
            }
        });
        vm.infoDate.insuranceNum = needInsuranceNum;
        vm.infoDate.guysShowText = `已选${vm.infoDate.guysList.length}人`;
        vm.infoDate.guysSelected = true;
    }
}

function saveVueData() {
    localStorage.setItem('DATA_book_room', JSON.stringify(vm.$data));
    localStorage.setItem('DATA_vmPopupDateBox', JSON.stringify(vmPopupDateBox.$data));
}

async function submit() {
    let startDay = vmPopupDateBox.selectDate.startDay;
    let endDay = vmPopupDateBox.selectDate.endDay;
    if (!endDay) {
        toast('请选择预定日期');
        return;
    }
    if (vm.infoDate.guysList.length < 1) {
        toast('请选择入住人');
        return;
    }
    let notGuyNeedInsurance = true;
    const reqData = {
        startDate: `${startDay.year}/${startDay.month}/${startDay.day}`,
        endDate: `${endDay.year}/${endDay.month}/${endDay.day}`,
        guest: (() => {
            return vm.infoDate.guysList.map(guy => {
                if (guy.needInsurance) {
                    notGuyNeedInsurance = false;
                }
                return {
                    id: guy.guest_info_id,
                    isInsurance: +!!guy.needInsurance,
                };
            });
        })(),
        houseId: getHouseId(),
    };
    if (notGuyNeedInsurance) {
        toast('请选择住宿意外险');
        return;
    }
    const close = fxj.dialog.loading();
    const res = await ajax({
        url: 'home/order/submit',
        data: reqData,
    });
    close();
    if (res.err === 0) {
        localStorage.removeItem('DATA_vmPopupDateBox');
        localStorage.removeItem('DATA_book_room');
        localStorage.removeItem('guysIdList');
        mui.toast(res.msg);
        setTimeout(() => {
            location.replace('place_order_succeed.html');
        }, 1000);
    }
    else {
        toast(res.msg);
    }
}

function setPrice(rent) {
    vm.roomSubmit.rent = rent;
    let insure = 0;
    vm.infoDate.guysList.forEach(guy => {
        if (guy.needInsurance) {
            insure += 0.5;
        }
    });
    if (insure > 0) {
        insure -= 0.5; // 免费一人
    }
    insure *= Number(vm.infoDate.nightNum);
    vm.roomSubmit.insure = insure;
    vm.roomSubmit.total = Number.isNaN(Number(vm.roomSubmit.deposit) + insure + rent) ? 0 : Number(vm.roomSubmit.deposit) + insure + rent;
}

async function reqHouseInfo() {
    const res = await ajax({
        url: 'home/order/getOrderHouse',
        data: {
            houseId: getHouseId(),
        },
    });
    res.data.img = fxj.fixImgUrl(res.data.img);
    vm.houseInfo = res.data;
    vm.roomSubmit.deposit = res.data.deposit;
}

function goInsure() {
    if (!vm.infoDate.guysSelected) {
        toast('请添加入住人');
        return;
    }
    saveVueData();
    go('zhu_su_yi_wai_xian.html');
}

async function getRentPrice() {
    let startDay = vmPopupDateBox.selectDate.startDay;
    let endDay = vmPopupDateBox.selectDate.endDay;
    if (!endDay) return;
    const reqData = {
        startDate: `${startDay.year}/${startDay.month}/${startDay.day}`,
        endDate: `${endDay.year}/${endDay.month}/${endDay.day}`,
        houseId: getHouseId(),
    };
    const res = await ajax({
        url: 'home/order/estimatedAmount',
        data: reqData,
    });
    return Number(res.data);
}

function back() {
    localStorage.removeItem('DATA_vmPopupDateBox');
    localStorage.removeItem('DATA_book_room');
    localStorage.removeItem('guysIdList');
    fxj.closeWin();
}

function addGuy() {
    if (!vmPopupDateBox.selectDate.endDay) {
        toast('请选择预定日期');
        return;
    }
    go('add_check_in_person.html', {
        data: {
            type: 'add',
        },
    });
}